//用户
(function() {
    var db_table_name = "user";
    var db = require("../db/index");
    var md5 = require("../_include/md5");
    var helper = require("../_include/helper");

    //构造函数
    var _con = function(info, isAnonymous, is_bus) {
        console.log(info);
        var self = this;
        //类别标识
        self.type = "user";
        //身份编号
        self._id = "U_" + Math.random().toString(16).substr(2) + (+new Date).toString(16);
        //操作记录
        self._his = [];
        //订单列表
        self.achs = [];
        //收获地址
        self.uas = [];
        //默认收货地址
        self.default_ua_id;
        //额外信息
        self.info = {}; //info;

        //初始化用户名
        info.name || (info.name = info.mobile_phone);
        if (!info.name) {
            throwCusError("用户名不可为空")
        }
        //名字不区分大小写
        if (db.find_one(db_table_name, {
                info: {
                    name: info.name
                }
            })) {
            throwCusError("用户名已经存在");
        }
        info.name = info.name.toLowerCase();
        if (!helper.folder_name(info.name)) {
            throwCusError("用户名命名不规范")
        }
        self.info.name = info.name;
        //从哪个商家站点进行注册
        var bus_id = info.register_bus_id;
        if (bus_id) {
            var bus = BusCon.get(bus_id);
            if (bus) {
                self.info.register_bus_id = bus_id;
                bus._addRegisterUser(self._id);
            }
        }
        //被哪个用户邀请注册
        var recommender_id = info.recommender_id;
        if (recommender_id) {
            var recommender = UserCon.get(recommender_id);
            if (recommender) {
                self.info.recommender_id = recommender_id;
                recommender._addRegisterUser(self._id);
            }
        }
        //当商家作为用户登录时，对应的用户，必须有这个bus_id标识
        if (is_bus) {
            self.bus_id = info.bus_id;
        }

        // //真实姓名
        // self.info.real_name = info.real_name||"";
        // //绑定的手机
        // self.info.mobile_phone = info.mobile_phone||"";
        // //绑定的邮箱
        // self.info.email = info.email||"";
        // //身份证
        // self.info.id_card = info.id_card||"";
        self.setInfo(info);

        //密码非明文存储
        self.info.password = md5.md5_2(info.password);
        //推荐积分
        self.rec_int = 0;
        //购买积分
        self.buy_int = 0;
        //购物车商品
        self.cart = [];
        //收藏夹（商品）
        self.collect = [];
        //收藏商家
        self.collectBus = [];
        //评价
        self.evaluations = [];
        //评论（包括评价）
        self.comments = [];
        //收到的回复
        self.replys = [];
        //账号状态：正常、冻结（被举报并查出有问题）
        self.status = "未审核";
        //账号类别：正常、VIP
        self.type = "正常";
        //正在起作用的BUFF
        self.buffs = [];
        //商品二进制订单
        self.bina_ach_list = [];
        //被自己邀请注册的用户
        self.register_users = [];

        if (isAnonymous) {
            //保存用户信息
            db.insert(db_table_name, self);
            //日志打印
            console.log("临时生成了一个匿名用户：", info.name);
        } else {
            //保存用户信息
            db.insert(db_table_name, self);
            //日志打印
            console.log("注册了一个用户：", info.name);
        }
    };
    //PS:模块的暴露放在require skill前面，因为二者互相依赖
    module.exports = _con;
    //技能
    _con.prototype = require("./skill");

    //不被JSON.stringify获取的属性
    _con.init_nojson_able_keys = function(obj) {
        var nojson_able_keys = ["recommender_map"];
        Object.keys(obj).forEach(function(key) {
            if (obj[key] instanceof Array) {
                nojson_able_keys.push(key);
            }
        });
        //排除白名单对象
        var white_list = ["collectBus", "collect", "card_list"];
        white_list.forEach(function(key) {
            var _white_index = nojson_able_keys.indexOf(key);
            _white_index !== -1 && nojson_able_keys.splice(_white_index, 1);
        });
        //保存key
        if (obj.nojson_able_keys instanceof Array) {
            obj.nojson_able_keys = nojson_able_keys;
        } else {
            Object.defineProperty(obj, "nojson_able_keys", {
                enumerable: false,
                value: nojson_able_keys
            });
        }

        if (!(obj.info.nojson_able_keys instanceof Array)) { //固定黑名单
            Object.defineProperty(obj.info, "nojson_able_keys", {
                enumerable: false,
                value: ["password"]
            });
        }
        return obj;
    };
    //静态方法xuezi
    _con.getByOpenId = function(obj) {
        var _u_a;
        var _u_b;
        console.log('getByOpenId', obj)
        if (obj.unionid) {
            _u_a = db.find_one(db_table_name, {
                info: {
                    weixin_unionid: obj.unionid
                }
            });
        };
        if (_u_a) {
            return _con.getInstance(_u_a);
        } else {
            _u_b = db.find_one(db_table_name, {
                info: {
                    weixin_openid: obj.openid
                }
            });
            console.log('getByOpenId', _u_b)
        };
        if (_u_b) {
            return _con.getInstance(_u_b);
        } else {
            throwCusError("当前微信号未绑定用户")
        }
    };
    //静态方法
    _con.get = function(Id) {
        var result = db.find_by_id(db_table_name, Id);
        result = _con.getInstance(result);
        return result;
    };
    _con.has = function(Id) {
        return !!db.find_by_id(db_table_name, Id);
    };
    _con.getInstance = function(obj) {
        if (obj) {
            obj = _con.init_nojson_able_keys(obj);
            obj.__proto__ = _con.prototype;
        }
        return obj;
    }
    _con.getAnonymous = function() {
        return new _con({
            name: "Anonymous",
            isAnonymous: true,
            email: "Anonymous@Anonymous.com",
            password: "mywebsite.com"
        }, true);
    };
    _con.login = function(user_info) {
        console.log(user_info)
        if (!user_info.name) {
            throwCusError("用户名不可为空");
        }
        if (!user_info.password) {
            throwCusError("密码不可为空");
        }
        user_info.name = user_info.name.toLowerCase();
        //用户名不再用于登录
        var mybey_user = db.find_one(db_table_name, {
            info: {
                name: user_info.name
            }
        });
        if (!mybey_user) { //手机号码登录
            var mybey_user = db.find_one(db_table_name, {
                info: {
                    mobile_phone: user_info.name
                }
            });
        }
        if (!mybey_user) { //邮箱登录
            var mybey_user = db.find_one(db_table_name, {
                info: {
                    email: user_info.name
                }
            });
        }
        if (!mybey_user) {
            console.log("找不到用户名为：“", user_info.name, "”的用户！");
            throwCusError("找不到指定用户名的用户");
        } else if (mybey_user.info.password !== md5.md5_2(user_info.password)) {
            console.log("密码错误！", user_info.password);
            throwCusError("密码错误");
        } else {
            console.log(user_info.name, "登陆成功");
            return _con.getInstance(mybey_user);
        }
    };
    _con.search = function(user_maybe_info) {
        if (!user_maybe_info) {
            return
        }
        var mybey_user = db.find_by_id(db_table_name, user_maybe_info);
        if (!mybey_user) { //用户名
            mybey_user = db.find_one(db_table_name, {
                info: {
                    name: user_maybe_info.toLowerCase()
                }
            });
        }
        if (!mybey_user) { //手机号码
            mybey_user = db.find_one(db_table_name, {
                info: {
                    mobile_phone: user_maybe_info
                }
            });
        }
        if (!mybey_user) { //邮箱
            mybey_user = db.find_one(db_table_name, {
                info: {
                    email: user_maybe_info
                }
            });
        }
        return _con.getInstance(mybey_user);
    };
    _con.find_by_weixin_openid = function(wx, openid) {
        var wx_user_info = wx.getUserInfo(openid);
        console.log("wx_user_info:", wx_user_info);
        var user_obj = db.find_one(db_table_name, {
            info: {
                weixin_unionid: wx_user_info.unionid
            }
        });
        if (!user_obj) {
            throwCusError("当前微信号未绑定用户")
        }
        console.log("user_obj.info:", user_obj.info);
        return _con.getInstance(user_obj);
    };

    var GoodsCon = require("../goods/_con");
    var UserCon = require("../user/_con");
    var BusCon = require("../bus/_con");
    var WX_V2 = require("../../my_modules/wx/wx.v2");
}());
